package ru.ifmo.croak.impl.replication.team1;

import java.net.SocketAddress;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class AliveHostsCollection {
    /**
     * thread safe Set
     */
    final Set<SocketAddress> aliveHostsTCPs;
    final Random random;

    public AliveHostsCollection() {
        aliveHostsTCPs = Collections.newSetFromMap(new ConcurrentHashMap<SocketAddress, Boolean>());
        random = new Random();

    }

    public void addAliveHost(SocketAddress socketAddress) {
        aliveHostsTCPs.add(socketAddress);
    }

    public void removeAliveHost(SocketAddress socketAddress) {
        aliveHostsTCPs.remove(socketAddress);
    }

    public SocketAddress getRandomAliveHost() {
        SocketAddress[] socketAddresses = aliveHostsTCPs.toArray(new SocketAddress[0]);
        if (socketAddresses.length == 0) {
            return null;
        }
        return socketAddresses[random.nextInt(socketAddresses.length)];
    }
}
